package com.erp.pro.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.erp.common.controller.BaseController;
import com.erp.common.utils.*;
import com.erp.pro.domain.*;
import com.erp.pro.service.*;
import com.erp.pur.domain.GroupDO;
import com.erp.pur.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 入库管理
 * 
 * @author Eric
 * @email shiliang900713@163.com
 * @date 2019-11-04 13:15:25
 */
 
@Controller
@RequestMapping("/pro/instock")
public class InstockController extends BaseController {
	@Autowired
	private InstockService instockService;

	@Autowired
	private WarehouseService warehouseService;

	@Autowired
	private GroupService groupService;

	@Autowired
	private ProductQtyService productQtyService;

	@Autowired
	private ProductService productService;
	@Autowired
	private SupplierService supplierService;
	
	@GetMapping()
	String Instock(){
	    return "pro/instock/instock";
	}
	
	@ResponseBody
	@GetMapping("/list")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<InstockDO> instockList = instockService.list(query);
		int total = instockService.count(query);
		PageUtils pageUtils = new PageUtils(instockList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	String add(){
	    return "pro/instock/add";
	}

	@GetMapping("/edit/{id}")
	String edit(@PathVariable("id") Integer id,Model model){
		InstockDO instock = instockService.get(id);
		model.addAttribute("instock", instock);
		List<GroupDO> groupDOList = groupService.list(null);
		model.addAttribute("groupDOList", groupDOList);
		List<WarehouseDO> warehouseDOList = warehouseService.list(null);
		model.addAttribute("warehouseDOList", warehouseDOList);
	    return "pro/instock/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	public R save( InstockDO instock){
		setInstock(instock);
		instock.setStatus(1);
		instock.setCreateTime(new Date());
		if(instockService.save(instock)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	public R update( InstockDO instock){
		setInstock(instock);
		instockService.update(instock);
		return R.ok();
	}

	private void setInstock(InstockDO instock) {
		if(instock.getWarehouseId() != null && instock.getWarehouseId()>0){
			WarehouseDO warehouseDO = warehouseService.get(Long.valueOf(instock.getWarehouseId()));
			if(warehouseDO != null){
				instock.setWarehouseName(warehouseDO.getName());
			}
		}else if(instock.getWarehouseName() != null && instock.getWarehouseName().length()>0){
			WarehouseDO warehouseDO = warehouseService.findByName(instock.getWarehouseName());
			if(warehouseDO != null){
				instock.setWarehouseId(warehouseDO.getId().intValue());
				instock.setWarehouseName(warehouseDO.getName());
			}
		}
		instock.setInqtyOperid(getUserId());
		instock.setInqtyOpername(getUser().getName());
		instock.setInqtyTime(new Date());
	}

	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	public R remove( Integer id){
		if(instockService.remove(id)>0){
		return R.ok();
		}
		return R.error();
	}

	/**
	 * 入库
	 * @param id
	 * @return
	 */
	@PostMapping( "/confirm")
	@ResponseBody
	public R confirm( Integer id){
		//添加库存
		//1.查询对应的仓库有没数据
		InstockDO instock = instockService.get(id);
		if(instock != null){
			ProductQtyDO productQtyDO = productQtyService.getQtyInfo(Long.valueOf(instock.getSkuId()),Long.valueOf(instock.getWarehouseId()));
			if(productQtyDO != null) {
				productQtyDO.setQty(productQtyDO.getQty() + instock.getInqty());
				productQtyService.update(productQtyDO);
			}else {
				//查询仓库信息
				WarehouseDO warehouseDO = warehouseService.get(Long.valueOf(instock.getWarehouseId()));
				productQtyDO = new ProductQtyDO();
				productQtyDO.setWarName(warehouseDO.getName());
				productQtyDO.setWarId(warehouseDO.getId());
				productQtyDO.setSku(instock.getSku());
				productQtyDO.setProId(Long.valueOf(instock.getSkuId()));
				productQtyDO.setQty(instock.getInqty());
				productQtyService.save(productQtyDO);
			}
			//计算SKU的总库存
			int allqty = productQtyService.getAllQty(Long.valueOf(instock.getSkuId()));
			ProductDO productDO = new ProductDO();
			productDO.setId(Long.valueOf(instock.getSkuId()));
			productDO.setAllQty(allqty);
			productService.update(productDO);
			//修改状态
			if(instockService.confirm(id)>0){
				return R.ok();
			}else{
				return R.error("修改状态失败");
			}
		}else{
			return R.error("ID不存在");
		}
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	public R remove(@RequestParam("ids[]") Integer[] ids){
		instockService.batchRemove(ids);
		return R.ok();
	}

	@GetMapping("/importexcel")
	String importexcel(){
		return "pro/instock/importexcel";
	}

	@GetMapping("/downloadTemplate")
	@ResponseBody
	void downloadTemplate(HttpServletResponse response){
		List<InstockDO> instockList = new ArrayList<>();
		ExcelUtil.exportExcel(instockList,"入库清单","入库清单",InstockDO.class,"入库清单.xls",response);
	}


	@PostMapping("/importInfo")
	public String importInfo(@RequestParam("file") MultipartFile file) {
		System.out.println("asdasdasdasdas");
		ImportParams importParams = new ImportParams();
		// 数据处理
		importParams.setHeadRows(1);
		importParams.setTitleRows(1);
		// 需要验证
		importParams.setNeedVerfiy(false);
		try{
			ExcelImportResult<InstockDO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), InstockDO.class,
					importParams);
			List<InstockDO> instockDOList = result.getList();
			if(instockDOList != null && instockDOList.size()>0){
				for (InstockDO instock:instockDOList) {
					if(StringUtils.isNotBlank(instock.getSku())){
						//查询商品信息
						ProductDO productDO = productService.getskuinfo(instock.getSku());
						if(productDO != null){
							instock.setSkuId(productDO.getId().intValue());
							instock.setProName(productDO.getName());
							instock.setProModel(productDO.getProModel());
							instock.setProSpec(productDO.getProSpec());
							instock.setProBrand(productDO.getProBrand());
							instock.setPicOrigin(productDO.getPicOrigin());
						}else{
							System.out.println("SKU不存在");
						}

						//查询采购合同
						GroupDO groupDO = groupService.getByGroupid(instock.getGroupid());
						if(groupDO != null){
							instock.setPurGropupId(groupDO.getId().intValue());
							instock.setSupplierId(groupDO.getSupplierId().intValue());
							instock.setSupplierName(groupDO.getSupplierName());
						}
						if(instock.getInqty() != null && instock.getInqty()>0 ){
							if(instock.getPurPrice() != null && instock.getPurPrice()>0){
								instock.setAllPrice(instock.getInqty()*instock.getPurPrice());
							}
							if(instock.getTaxRate() != null && instock.getTaxRate()>0){
								instock.setNoTaxPrice(instock.getPurPrice()*(1-instock.getTaxRate()));
							}
						}
						setInstock(instock);
						instock.setStatus(1);
						instock.setCreateTime(new Date());
						instockService.save(instock);
					}else{
						System.out.println("SKU不存在");
					}
				}
			}else{
				System.out.println("表格为空");
			}
			return "导入成功";
		}catch (IOException e) {
			System.out.println(e.getMessage());
			return "e:导入失败";
		} catch (Exception e1) {
			e1.printStackTrace();
			System.out.println(e1.getMessage());
			return "e1:导入失败";
		}
	}

	@ResponseBody
	@GetMapping("/getgrouplist/{proid}")
	public List<InstockDO> getgrouplist(@PathVariable("proid")Long proid){
		List<InstockDO> instockDOList =  instockService.findByOutQty(proid);
		return instockDOList;
	}

	@ResponseBody
	@GetMapping("/getInfo/{id}")
	public  InstockDO getInfo(@PathVariable("id")Integer id){
		InstockDO instockDO =  instockService.get(id);
		return instockDO;
	}

	@GetMapping("/instockbysku/{proId}")
	String edittab(@PathVariable("proId") Long proId, Model model){
		model.addAttribute("proId",proId);
		return "pro/instock/qtylistbysku";
	}

	@ResponseBody
	@GetMapping("/instocklistbysku")
	public PageUtils instocklistbysku(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<InstockDO> instockList = instockService.list(query);
		int total = instockService.count(query);
		PageUtils pageUtils = new PageUtils(instockList, total);
		return pageUtils;
	}


	@PostMapping("/exportData")
	@ResponseBody
	public void downloadTemplate(InstockDO instockDO, HttpServletResponse response){
		//ProjectDO project
		Map<String, Object> params = new HashMap<>();
		if(StringUtils.isNotBlank(instockDO.getSupplierName())){
			params.put("supplierName",instockDO.getSupplierName());
		}
		if(StringUtils.isNotBlank(instockDO.getProModel())){
			params.put("proModel",instockDO.getProModel());
		}
		if(StringUtils.isNotBlank(instockDO.getSku())){
			params.put("sku",instockDO.getSku());
		}
		if(StringUtils.isNotBlank(instockDO.getProBrand())){
			params.put("proBrand",instockDO.getProBrand());
		}
		if(StringUtils.isNotBlank(instockDO.getWarehouseName())){
			params.put("warehouseName",instockDO.getWarehouseName());
		}
		List<InstockDO> instockDOList = instockService.list(params);
		ExcelUtil.exportExcel(instockDOList,"入库列表","入库列表",InstockDO.class,"入库列表.xls",response);
	}

}
